package wxutils

import (
	"bytes"
	"encoding/json"
	"end/httpEntry"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"io/ioutil"
	"net/http"
)

const appID = "wxd6ad672beb698488"
const appSecret = "6642916c92dd5832b3a5294922230d95"

func GetOpenid(r *gin.Engine) {
	type WechatSessionResponse struct {
		OpenID string `json:"openid"`
		// 根据需要，可以添加其他字段，例如 session_key, unionid 等
	}
	r.GET("/wxutils/openid/:jsCode", func(context *gin.Context) {
		jsCode := context.Param("jsCode")
		url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appID, appSecret, jsCode)
		// 发起HTTP GET请求
		resp, err := http.Get(url)
		if err != nil {
			return
		}
		defer func(Body io.ReadCloser) {
			err := Body.Close()
			if err != nil {

			}
		}(resp.Body)

		// 读取响应内容
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			return
		}

		// 解析JSON数据
		var wechatResp WechatSessionResponse
		err = json.Unmarshal(body, &wechatResp)
		if err != nil {
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"data": wechatResp.OpenID,
		})
	})
}

func GetAccessToken(r *gin.Engine) {
	// 定义一个结构体来接收响应数据
	type WechatResponse struct {
		AccessToken string `json:"access_token"`
		// 可以根据实际情况添加其他需要的字段
	}
	r.GET("/wxutils/accessToken", func(context *gin.Context) {
		// 发起HTTP GET请求
		url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appID, appSecret)
		resp, err := http.Get(url)
		if err != nil {
			// 处理请求错误
			fmt.Println("请求失败:", err)
			return
		}
		defer func(Body io.ReadCloser) {
			err := Body.Close()
			if err != nil {

			}
		}(resp.Body)

		// 读取响应内容
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			// 处理响应错误
			fmt.Println("读取响应失败:", err)
			return
		}
		// 解析JSON数据
		var wechatResp WechatResponse
		err = json.Unmarshal(body, &wechatResp)
		if err != nil {
			// 处理JSON解析错误
			fmt.Println("解析JSON失败:", err)
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"data": wechatResp.AccessToken,
		})
		// 输出AccessToken
	})
}

type PhoneNumberRequest struct {
	Code string `json:"code"`
}

type PhoneNumberResponse struct {
	PhoneInfo struct {
		PhoneNumber string `json:"phoneNumber"`
	} `json:"phone_info"`
}

func getUserPhoneNumber(accessToken, code string) (*PhoneNumberResponse, error) {
	url := "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken
	requestData := PhoneNumberRequest{
		Code: code,
	}

	// 将请求数据转换为JSON
	jsonData, err := json.Marshal(requestData)
	if err != nil {
		return nil, fmt.Errorf("编码JSON失败: %v", err)
	}

	// 发起HTTP POST请求
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, fmt.Errorf("请求失败: %v", err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %v", err)
	}

	// 解析JSON数据
	var phoneResp PhoneNumberResponse
	err = json.Unmarshal(body, &phoneResp)
	if err != nil {
		return nil, fmt.Errorf("解析JSON失败: %v", err)
	}

	return &phoneResp, nil
}

func GetPhoneNumber(r *gin.Engine) {

	type PhoneRequest struct {
		AccessToken string `json:"accessToken" binding:"required"`
		Code        string `json:"code" binding:"required"`
	}

	r.POST("/wxutils/phone", func(context *gin.Context) {
		var phoneRequest PhoneRequest
		err := context.ShouldBind(&phoneRequest)
		if err != nil {
			return
		}
		phoneResp, err := getUserPhoneNumber(phoneRequest.AccessToken, phoneRequest.Code)
		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: err.Error(),
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"data": phoneResp.PhoneInfo.PhoneNumber,
		})
	})
}
